package com.tanhua.recommend.listener;

import com.alibaba.fastjson.JSON;
import com.tanhua.domain.mongo.VideoScore;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
@RocketMQMessageListener(topic = "tanhua-video", consumerGroup = "tanhua-video-consumer")
public class VideoScoreListener implements RocketMQListener<String> {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void onMessage(String message) {
        // 1.解析消息
        Map<String, Object> map = JSON.parseObject(message, Map.class);
        Integer type = Integer.valueOf(map.get("type").toString());
        Long userId = Long.valueOf(map.get("userId").toString());
        String videoId = (String) map.get("videoId");
        Long vid = Long.valueOf(map.get("vid").toString());

        // 2.创建评分数据对象
        VideoScore videoScore = new VideoScore();
        videoScore.setUserId(userId);
        videoScore.setVideoId(vid);
        videoScore.setDate(System.currentTimeMillis());

        // 3.计算得分
        // type 类型 1-发布小视频，2-点赞，3-取消点赞，4-评论
        switch (type) {
            case 1:
                videoScore.setScore(2D);
                break;

            case 2:
                videoScore.setScore(5D);
                break;

            case 3:
                videoScore.setScore(-5D);
                break;

            case 4:
                videoScore.setScore(10D);
                break;
        }

        // 保存评分数据到mongoDB
        mongoTemplate.save(videoScore);

    }
}
